package com.aos.erp.message.service.impl;

import com.aos.erp.common.bean.PageBean;
import com.aos.erp.common.dao.mapper.Condition;
import com.aos.erp.common.exception.BizException;
import com.aos.erp.common.utils.DateUtils;
import com.aos.erp.message.dto.MessageTemplateDTO;
import com.aos.erp.message.dto.MessageTemplateItemDTO;
import com.aos.erp.message.enums.DelStatus;
import com.aos.erp.message.enums.PushType;
import com.aos.erp.message.mapper.*;
import com.aos.erp.message.model.*;
import com.aos.erp.message.model.vo.*;
import com.aos.erp.message.service.MessageTemplateService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class MessageTemplateServiceImpl extends ServiceImpl<MessageTemplateMapper, MessageTemplateInfo> implements MessageTemplateService {

    @Resource
    private MTDriverSchoolMapper driverSchoolMapper;
    @Resource
    private MTContentAppMapper contentAppMapper;
    @Resource
    private MTContentSmsMapper contentSmsMapper;
    @Resource
    private MTContentWxPublicMapper contentWxPublicMapper;
    @Resource
    private MTContentWxAppletMapper contentWxAppletMapper;
    @Resource
    private MTPushTypeMapper pushTypeMapper;
    @Resource
    private MTPushTypeParamMapper pushTypeParamMapper;

    @Override
    public void saveTemplate(MessageTemplateVo dataInfo) throws BizException {

        checkSaveTemplateData(dataInfo);

        // 保存新消息模板：模板编号、模板标题、推送方式，获得模板ID
        long mtId = saveMessageTemplate(dataInfo);

        // 保存适用驾校
        saveDriverSchool(mtId, dataInfo.getMtDriverSchoolList());

        // 保存推送方式
        savePushType(mtId, dataInfo.getPushTypeList());

        // 保存模板内容
        for (MTPushTypeVo pushTypeVo : dataInfo.getPushTypeList()) {
            if(pushTypeVo.getPushType() == PushType.app) {
                // APP推送模板：模板ID、模板内容
                saveContentApp(mtId, pushTypeVo.getMtContent());
            } else if(pushTypeVo.getPushType() == PushType.wx_public) {
                // 微信公众号模板：模板ID、微信模板ID、点击模板后跳转链接
                saveContentWxPublic(mtId, pushTypeVo.getMtWxTemplateId(), pushTypeVo.getMtUrl(), pushTypeVo.getMtContent());
            } else if(pushTypeVo.getPushType() == PushType.wx_applet) {
                // 微信小程序模板：模板ID、微信模板ID、点击模板后跳转链接（仅限本小程序内的页面）
                saveContentWxApplet(mtId, pushTypeVo.getMtWxTemplateId(), pushTypeVo.getMtUrl(), pushTypeVo.getMtContent());
            } else if(pushTypeVo.getPushType() == PushType.sms) {
                // 短信模板：模板ID、模板内容
                saveContentSms(mtId, pushTypeVo.getMtContent());
            }
        }

    }

    @Override
    public void deleteTemplate(String dataId) throws BizException {

        if(dataId.isEmpty()) {
            throw new BizException("模板ID不能为空");
        }
        baseMapper.deleteTemplate(dataId);
    }

    @Override
    public void updateTemplate(MessageTemplateVo dataInfo) throws BizException {

        checkUpdateTemplateData(dataInfo);

        // 保存消息模板：模板编号、模板标题、推送方式
        baseMapper.updateTemplate(dataInfo);
//        updateMessageTemplate(dataInfo);
        long mtId = dataInfo.getId();

        // 保存适用驾校
        // 删除旧记录
        Condition dsCondition = new Condition(MTDriverSchoolInfo.class);
        dsCondition.eqFiled("mtId", mtId);
        driverSchoolMapper.delete(dsCondition.getWrapper());

        // 保存新记录
        saveDriverSchool(mtId, dataInfo.getMtDriverSchoolList());

        // 保存推送方式
        // 删除推送参数旧记录
        Condition ptpCondition = new Condition(MTPushTypeParam.class);
        ptpCondition.eqFiled("mtId", mtId);
        pushTypeParamMapper.delete(ptpCondition.getWrapper());

        // 删除推送方式旧记录
        Condition ptCondition = new Condition(MTPushType.class);
        ptCondition.eqFiled("mtId", mtId);
        pushTypeMapper.delete(ptCondition.getWrapper());

        // 保存新记录
        savePushType(mtId, dataInfo.getPushTypeList());

        // 保存模板内容
        for (MTPushTypeVo pushTypeVo : dataInfo.getPushTypeList()) {
            if(pushTypeVo.getPushType() == PushType.app) {
                // APP推送模板：模板ID、模板内容
                int updateCount = contentAppMapper.updateContent(mtId, pushTypeVo.getMtContent());
                if(updateCount == 0) {
                    saveContentApp(mtId, pushTypeVo.getMtContent());
                }
            } else if(pushTypeVo.getPushType() == PushType.wx_public) {
                // 微信公众号模板：模板ID、微信模板ID、点击模板后跳转链接
                int updateCount = contentWxPublicMapper.updateContent(mtId, pushTypeVo.getMtWxTemplateId(), pushTypeVo.getMtUrl(), pushTypeVo.getMtContent());
                if(updateCount == 0) {
                    saveContentWxPublic(mtId, pushTypeVo.getMtWxTemplateId(), pushTypeVo.getMtUrl(), pushTypeVo.getMtContent());
                }
            } else if(pushTypeVo.getPushType() == PushType.wx_applet) {
                // 微信小程序模板：模板ID、微信模板ID、点击模板后跳转链接（仅限本小程序内的页面）
                int updateCount = contentWxAppletMapper.updateContent(mtId, pushTypeVo.getMtWxTemplateId(), pushTypeVo.getMtUrl(), pushTypeVo.getMtContent());
                if(updateCount == 0) {
                    saveContentWxApplet(mtId, pushTypeVo.getMtWxTemplateId(), pushTypeVo.getMtUrl(), pushTypeVo.getMtContent());
                }
            } else if(pushTypeVo.getPushType() == PushType.sms) {
                // 短信模板：模板ID、模板内容
                int updateCount = contentSmsMapper.updateContent(mtId, pushTypeVo.getMtContent());
                if(updateCount == 0) {
                    saveContentSms(mtId, pushTypeVo.getMtContent());
                }
            }
        }
    }

    @Override
    public MessageTemplateDTO getTemplateDetail(long dataId) {
        // 获取消息模板详情
        MessageTemplateInfo templateInfo = baseMapper.selectById(dataId);
        // 获取消息模板分配驾校列表
        Condition condition = new Condition(MTDriverSchoolInfo.class);
        condition.eqFiled("mtId", dataId);
        List<MTDriverSchoolInfo> driverSchoolInfoList = driverSchoolMapper.selectList(condition.getWrapper());

        MessageTemplateDTO messageTemplateDTO = new MessageTemplateDTO();
        messageTemplateDTO.setMessageTemplate(templateInfo);
        messageTemplateDTO.setDriverSchoolInfoList(driverSchoolInfoList);

        // 获取推送方式列表
        Condition pushTypeCondition = new Condition(MTPushType.class);
        pushTypeCondition.eqFiled("mtId", dataId);
        List<MTPushType> pushTypeList = pushTypeMapper.selectList(pushTypeCondition.getWrapper());

        for (MTPushType pushType : pushTypeList) {

            // 推送
            messageTemplateDTO.getPushTypeList().add(pushType.getPushType());

            // 推送参数
            Condition paramCondition = new Condition(MTPushTypeParam.class);
            paramCondition.eqFiled("mtId", dataId);
            paramCondition.eqFiled("ptId", pushType.getId());
            List<MTPushTypeParam> paramList = pushTypeParamMapper.selectList(paramCondition.getWrapper());

            // 查询模板内容
            if(pushType.getPushType() == PushType.app) {

                // APP推送模板
                Condition contentCondition = new Condition(MTContentAppInfo.class);
                contentCondition.eqFiled("mtId", dataId);
                MTContentAppInfo contentInfo = contentAppMapper.selectOne(contentCondition.getWrapper());
                if(contentInfo != null) {
                    messageTemplateDTO.setMtContentForApp(contentInfo.getMtContent());
                }
                // APP 推送参数
                if(paramList != null) {
                    messageTemplateDTO.setAppPushParamList(paramList);
                }

            } else if(pushType.getPushType() == PushType.wx_public) {
                // 微信公众号模板
                Condition contentCondition = new Condition(MTContentWxPublicInfo.class);
                contentCondition.eqFiled("mtId", dataId);
                MTContentWxPublicInfo contentInfo = contentWxPublicMapper.selectOne(contentCondition.getWrapper());
                if(contentInfo != null) {
                    messageTemplateDTO.setMtWxTemplateIdForPublic(contentInfo.getMtWxTemplateId());
                    messageTemplateDTO.setMtUrlForPublic(contentInfo.getMtUrl());
                    messageTemplateDTO.setMtContentForPublic(contentInfo.getMtContent());
                }
                // 微信公众号 推送参数
                if(paramList != null) {
                    messageTemplateDTO.setPublicPushParamList(paramList);
                }
            } else if(pushType.getPushType() == PushType.wx_applet) {
                // 微信小程序模板
                Condition contentCondition = new Condition(MTContentWxAppletInfo.class);
                contentCondition.eqFiled("mtId", dataId);
                MTContentWxAppletInfo contentInfo = contentWxAppletMapper.selectOne(contentCondition.getWrapper());
                if(contentInfo != null) {
                    messageTemplateDTO.setMtWxTemplateIdForApplet(contentInfo.getMtWxTemplateId());
                    messageTemplateDTO.setMtUrlForApplet(contentInfo.getMtUrl());
                    messageTemplateDTO.setMtContentForApplet(contentInfo.getMtContent());
                }
                // 微信小程序 推送参数
                if(paramList != null) {
                    messageTemplateDTO.setAppletPushParamList(paramList);
                }
            } else if(pushType.getPushType() == PushType.sms) {
                // 短信模板
                Condition contentCondition = new Condition(MTContentSmsInfo.class);
                contentCondition.eqFiled("mtId", dataId);
                MTContentSmsInfo contentInfo = contentSmsMapper.selectOne(contentCondition.getWrapper());
                if(contentInfo != null) {
                    messageTemplateDTO.setMtContentForSms(contentInfo.getMtContent());
                    messageTemplateDTO.setMtSmsTemplateId(contentInfo.getMtSmsTemplateId());
                }
                // 短信 推送参数
                if(paramList != null) {
                    messageTemplateDTO.setSmsPushParamList(paramList);
                }
            }
        }
        return messageTemplateDTO;
    }

    @Override
    public PageBean<MessageTemplateItemDTO> findByPage(MTConditionVo conditionVo) {
        Page<MessageTemplateItemDTO> page = new Page<MessageTemplateItemDTO>(conditionVo.getPageIndex(), conditionVo.getPageSize());
        List<MessageTemplateItemDTO> noticeInfoList = baseMapper.pageTemplateList(page, conditionVo);
        page.setRecords(noticeInfoList);

        PageBean<MessageTemplateItemDTO> bean = new PageBean<MessageTemplateItemDTO>(page.getCurrent(), page.getSize(), page.getTotal());
        bean.setOptimizeCountSql(page.optimizeCountSql());
        bean.setAscs(page.ascs());
        bean.setDescs(page.descs());
        bean.setRecords(page.getRecords());
        bean.condition();

        return bean;

//        IPage<MessageTemplateInfo> page = baseMapper.createPlusPage(conditionVo.getPageIndex(), conditionVo.getPageSize());
//        List<MessageTemplateInfo> noticeInfoList = baseMapper.pageTemplateList(page, conditionVo);
//        page.setRecords(noticeInfoList);
//        return (PageBean<MessageTemplateInfo>)baseMapper.toBizPage(page);
    }

    @Override
    public List<MessageTemplateInfo> findAll(Long dsId) {
        return baseMapper.allTemplateList(dsId);
    }

    @Override
    public MessageTemplateInfo getTemplateDetailByCode(String mtCode) {
        Condition contentCondition = new Condition(MessageTemplateInfo.class);
        contentCondition.eqFiled("mtCode", mtCode);
        contentCondition.eqFiled("isDel", DelStatus.del_no);
        return baseMapper.selectOne(contentCondition.getWrapper());
    }

    /**
     * 保存消息模板
     * @param dataInfo
     * @return
     */
    private long saveMessageTemplate(MessageTemplateVo dataInfo) {
        Date nowDate = new Date();
        MessageTemplateInfo templateData = new MessageTemplateInfo();
        templateData.setMtCode("MT" + DateUtils.getXXTimeString());
        templateData.setMtTitle(dataInfo.getMtTitle());
        templateData.setCreateUser(dataInfo.getOptUser());
        templateData.setUpdateUser(dataInfo.getOptUser());
        templateData.setCreateTime(nowDate);
        templateData.setUpdateTime(nowDate);
        this.save(templateData);
        return templateData.getId();
    }

    /**
     * 保存模板推送方式
     * @param mtId
     * @param pushTypeList
     */
    private void savePushType(long mtId, List<MTPushTypeVo> pushTypeList) {
        for (MTPushTypeVo pushTypeVo : pushTypeList) {

            // 保存推送方式
            MTPushType pushType = new MTPushType();
            pushType.setMtId(mtId);
            pushType.setPushType(pushTypeVo.getPushType());
            pushTypeMapper.insert(pushType);

            // 保存推送参数
            savePushTypeParam(mtId, pushType.getId(), pushTypeVo.getPushParamList());
        }
    }

    /**
     * 保存推送参数
     * @param mtId
     * @param pushTypeParamList
     */
    private void savePushTypeParam(long mtId, long ptId, List<MTPushTypeParamVo> pushTypeParamList) {
        for (MTPushTypeParamVo pushTypeParamVo : pushTypeParamList) {
            MTPushTypeParam pushTypeParam = new MTPushTypeParam();
            BeanUtils.copyProperties(pushTypeParamVo, pushTypeParam);
            pushTypeParam.setMtId(mtId);
            pushTypeParam.setPtId(ptId);
            pushTypeParamMapper.insert(pushTypeParam);
        }
    }

    /**
     * 保存模板分配驾校
     * @param mtId
     * @param driverSchoolList
     */
    private void saveDriverSchool(long mtId, List<MTDriverSchoolVo> driverSchoolList) {
        for (MTDriverSchoolVo dsr : driverSchoolList) {
            MTDriverSchoolInfo ds = new MTDriverSchoolInfo();
            ds.setMtId(mtId);
            ds.setDsId(dsr.getDsId());
            ds.setDsCode(dsr.getDsCode());
            ds.setDsName(dsr.getDsName());
            driverSchoolMapper.insert(ds);
        }
    }

    /**
     * 保存APP消息模板
     * @param mtId
     * @param mtContent
     */
    private void saveContentApp(long mtId, String mtContent) {
        MTContentAppInfo contentInfo = new MTContentAppInfo();
        contentInfo.setMtId(mtId);
        contentInfo.setMtContent(mtContent);
        contentAppMapper.insert(contentInfo);
    }

    /**
     *
     * 保存微信公众号消息模板
     * @param mtId
     * @param wxTemplateId
     * @param linkUrl
     * @param mtContent
     */
    private void saveContentWxPublic(long mtId, String wxTemplateId, String linkUrl, String mtContent) {
        MTContentWxPublicInfo contentInfo = new MTContentWxPublicInfo();
        contentInfo.setMtId(mtId);
        contentInfo.setMtWxTemplateId(wxTemplateId);
        contentInfo.setMtUrl(linkUrl);
        contentInfo.setMtContent(mtContent);
        contentWxPublicMapper.insert(contentInfo);
    }

    /**
     *
     * 保存微信小程序消息模板
     * @param mtId
     * @param wxTemplateId
     * @param linkUrl
     * @param mtContent
     */
    private void saveContentWxApplet(long mtId, String wxTemplateId, String linkUrl, String mtContent) {
        MTContentWxAppletInfo contentInfo = new MTContentWxAppletInfo();
        contentInfo.setMtId(mtId);
        contentInfo.setMtWxTemplateId(wxTemplateId);
        contentInfo.setMtUrl(linkUrl);
        contentInfo.setMtContent(mtContent);
        contentWxAppletMapper.insert(contentInfo);
    }

    /**
     * 保存短信模板
     * @param mtId
     * @param mtContent
     */
    private void saveContentSms(long mtId, String mtContent) {
        MTContentSmsInfo contentInfo = new MTContentSmsInfo();
        contentInfo.setMtId(mtId);
        contentInfo.setMtContent(mtContent);
        contentSmsMapper.insert(contentInfo);
    }

    private void checkTemplateData(MessageTemplateVo params)  throws BizException {
        if(params.getMtTitle().isEmpty()) {
            throw new BizException("模板标题不能为空");
        }
        if(params.getMtTitle().length() > 100) {
            throw new BizException("模板标题长度不能超过100");
        }
        if(params.getPushTypeList().size() == 0) {
            throw new BizException("推送方式不能为空");
        }
        for (MTPushTypeVo pushTypeVo : params.getPushTypeList()) {
            if(pushTypeVo.getPushType() == PushType.app) {
                if(pushTypeVo.getMtContent().isEmpty()) {
                    throw new BizException("APP模板内容不能为空");
                }
                if(pushTypeVo.getMtContent().length() > 1000) {
                    throw new BizException("APP模板内容长度不能超过1000");
                }
                if(pushTypeVo.getPushParamList().size() == 0) {
                    throw new BizException("APP推送参数不能为空");
                }
            }

            if(pushTypeVo.getPushType() == PushType.wx_public) {
                if(pushTypeVo.getMtWxTemplateId().isEmpty()) {
                    throw new BizException("微信公众号消息模板ID不能为空");
                }
                if(pushTypeVo.getPushParamList().size() == 0) {
                    throw new BizException("微信公众号推送参数不能为空");
                }
            }

            if(pushTypeVo.getPushType() == PushType.wx_applet) {
                if(pushTypeVo.getMtWxTemplateId().isEmpty()) {
                    throw new BizException("微信小程序消息模板ID不能为空");
                }
                if(pushTypeVo.getPushParamList().size() == 0) {
                    throw new BizException("微信小程序推送参数不能为空");
                }
            }
            if(pushTypeVo.getPushType() == PushType.sms) {
                if(pushTypeVo.getMtContent().isEmpty()) {
                    throw new BizException("短信模板内容不能为空");
                }
                if(pushTypeVo.getMtContent().length() > 1000) {
                    throw new BizException("短信模板内容长度不能超过1000");
                }
                if(pushTypeVo.getPushParamList().size() == 0) {
                    throw new BizException("短信推送参数不能为空");
                }
            }
        }
        if(params.getMtDriverSchoolList().size() == 0) {
            throw new BizException("模板分配驾校不能为空");
        }
    }

    private void checkSaveTemplateData(MessageTemplateVo params) throws BizException {
//        MessageTemplateInfo mtData = getTemplateDetailByCode(params.getMtCode());
//        if(mtData != null && mtData.getId() > 0) {
//            throw new BizException("模板编号已使用");
//        }
        checkTemplateData(params);
    }

    private void checkUpdateTemplateData(MessageTemplateVo params) throws BizException {

        if(params.getId() == 0) {
            throw new BizException("模板ID不能为空");
        }
        checkTemplateData(params);
    }
}
